/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DB;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author xgzheng
 */
public class OracleConnect {

    private final String oracleDriverName = "oracle.jdbc.driver.OracleDriver";
    private final String oracleUrlToConnect = "jdbc:oracle:thin:@localhost:1521:xe";
    private Connection myConnection = null;

    public OracleConnect() {
        try {
            Class.forName(oracleDriverName);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(OracleConnect.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public StringBuffer getErrorMessage(Exception ex, String alarmMessage) {
        StringBuffer errorStringBuffer = new StringBuffer();
        errorStringBuffer.append(alarmMessage);
        errorStringBuffer.append(ex.getMessage());
        return errorStringBuffer;
    }

    public Connection getConnection() {
        try {
            this.myConnection = DriverManager.getConnection(oracleUrlToConnect, "easy", "easy");

        } catch (Exception ex) {
            System.out.println(getErrorMessage(ex, "Can not get connection,please contact to your Software Designer!").toString());
        }
        return this.myConnection;
    }

    public static void main(String[] args) {

        OracleConnect myOracleTest = new OracleConnect();
        try {
            Connection myConnection = myOracleTest.getConnection();

            System.out.println("Now begin to excute.............");

            myConnection.setAutoCommit(false);

            PreparedStatement myPreparedStatement = myConnection.prepareStatement("select userid,uname,upwd from tbuser");
            //myPreparedStatement.setInt(1,2);
            ResultSet myResultSet = myPreparedStatement.executeQuery();
            StringBuffer myStringBuffer = new StringBuffer();
            while (myResultSet.next()) {
                myStringBuffer.append(myResultSet.getInt("userid") + "  ");
                myStringBuffer.append(myResultSet.getString("uname") + "  ");
                myStringBuffer.append(myResultSet.getString("upwd") + "  ");
            }
            System.out.println(myStringBuffer.toString());
            //System.out.println(new String(myStringBuffer.toString().getBytes("ISO-8859-1"),"GBK"));
        } catch (Exception ex) {
            System.out.println(myOracleTest.getErrorMessage(ex, "Application error,please contact to your Software Designer!").toString());
        }
    }
}
